<template>
    <div>
        <el-row style="margin-bottom: 9px;margin-left: 15px" :gutter="20">
            <el-col :span="6">
                <el-button size="small" :disabled="!addFlag" type="primary" @click="addProduct">新增</el-button>
                <el-button size="small" :disabled="!deleteFlag" type="danger" @click="deleteBatch">批量删除</el-button>
                <!--                <el-button size="small" type="success" @click="deleteBatch">详情添加</el-button>-->
            </el-col>
            <el-col style="display: flex" :span="6">
                <el-input
                        placeholder="请输入商品名称"
                        v-model="keywords"
                        clearable>
                </el-input>
                <el-button style="margin-left: 5px" type="success" plain>搜索</el-button>

            </el-col>
        </el-row>
        <el-card>
            <template>
                <el-table
                        @selection-change="handleSelectionChange"
                        size="mini"
                        :data="productList"
                        stripe
                        v-loading="loading"
                        style="">
                    <el-table-column
                            type="selection"
                    >
                    </el-table-column>

                    <el-table-column
                            prop="id"
                            label="id"
                    >
                    </el-table-column>
                    <el-table-column label="sku图片">
                        <template slot-scope="scope">
                            <el-image
                                    style="width: 50px; height: 50px"
                                    :src="scope.row.skuImg"
                                    :preview-src-list="[scope.row.skuImg]"
                            ></el-image>
                        </template>
                    </el-table-column>

                    <el-table-column
                            prop="productName"
                            label="商品名称"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="description"
                            label="介绍"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="categoryName"
                            label="商品分类">
                        <template slot-scope="scope">
                            <el-tag style="" v-for="item in scope.row.categoryName" size="mini">
                                {{item}}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column
                            prop="originalPrice"
                            label="原价"
                    >
                    </el-table-column>

                    <el-table-column
                            prop="sellPrice"
                            label="实际价格"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="discounts"
                            label="折扣力度"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="soldNum"
                            label="销售总量"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="stock"
                            label="库存"
                    >
                    </el-table-column>


                    <el-table-column
                            prop="formatTime"
                            label="创建时间">
                    </el-table-column>
                    <el-table-column style="" label="操作">
                        <template style="" slot-scope="scope">
                            <el-button
                                    :disabled="!updateFlag"
                                    @click="showEdit(scope.row)"
                                    size="mini" type="primary"
                                    icon="el-icon-edit"></el-button>
                            <el-tooltip class="item" effect="dark" content="详情添加" placement="top">
                                <el-button :disabled="!addFlag" title="详情添加" @click="toWrite(scope.row.id)" size="mini"
                                           type="warning"
                                           icon="el-icon-star-off"></el-button>
                            </el-tooltip>
                            <el-tooltip class="item" effect="dark" content="详情修改" placement="top">
                                <el-button :disabled="!updateFlag" type="info" @click="toEdit(scope.row.id)" size="mini"
                                           icon="el-icon-message"></el-button>
                            </el-tooltip>
                            <el-popconfirm
                                    @confirm="deleteCategory(scope.row)"
                                    title="这是一段内容确定删除吗？"
                            >
                                <el-button
                                        :disabled="!deleteFlag"
                                        size="mini"
                                        type="danger"
                                        icon="el-icon-delete"
                                        @click="handleDelete(scope.$index, scope.row)"
                                        slot="reference"
                                ></el-button>
                            </el-popconfirm>

                            <!--        修改对话框-->
                            <el-form :model="formEdit" ref="formEditRef" label-width="100px"
                                     class="demo-ruleForm">

                                <el-dialog
                                        @close="clearEdit(formAddRef)"
                                        title="修改产品信息"
                                        :visible.sync="dialogVisibleEdit"
                                        width="60%"
                                >
                                    <el-form-item label="产品名称" prop="name">
                                        <el-input v-model="formEdit.name"></el-input>
                                    </el-form-item>
                                    <el-form-item label="产品图" prop="img">
                                        <el-image
                                                style="width: 50px; height: 50px"
                                                :src="formEdit.img"
                                                :preview-src-list="[formEdit.img]"
                                        ></el-image>
                                    </el-form-item>
                                    <el-form-item label="原价" prop="originalPrice">
                                        <el-input v-model="formEdit.originalPrice"></el-input>
                                    </el-form-item>

                                    <el-form-item label="分类" prop="originalPrice">
                                        <el-tree
                                                ref="treeEdit"
                                                :data="categoryTree"
                                                show-checkbox
                                                node-key="id"
                                                :default-expanded-keys="typeIds"
                                                :default-checked-keys="typeIds"
                                                :props="defaultProps">
                                        </el-tree>
                                    </el-form-item>

                                    <el-form-item label="折扣" prop="discounts">
                                        <el-input v-model="formEdit.discounts"></el-input>
                                    </el-form-item>
                                    <el-form-item label="库存" prop="stock">
                                        <el-input v-model="formEdit.stock"></el-input>
                                    </el-form-item>
                                    <el-upload
                                            class="upload-demo"
                                            :action="baseUrl"
                                            multiple
                                            :limit="3"
                                            :on-success="uploadEdit"
                                    >
                                        <el-button size="small" type="primary">点击上传</el-button>
                                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                                    </el-upload>
                                    <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisibleEdit = false">取 消</el-button>
    <el-button type="primary" @click="submitEdit(scope.row)">确 定</el-button>
  </span>
                                </el-dialog>
                            </el-form>

                            <!--        修改对话框结束-->
                        </template>
                    </el-table-column>
                </el-table>
            </template>

        </el-card>
        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage4"
                :page-sizes="[1, 6]"
                :page-size="size"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
        </el-pagination>
        <!--        新增对话框开始-->
        <el-form :model="formAdd" ref="formAddRef" label-width="100px" class="demo-ruleForm">

            <el-dialog
                    @close="clearAdd(formAddRef)"
                    title="新增商品"
                    :visible.sync="dialogVisibleAdd"
                    width="30%"
            >

                <el-form-item label="商品名称" prop="name">
                    <el-input v-model="formAdd.name"></el-input>
                </el-form-item>

                <el-form-item label="原价" prop="orginalPrice">
                    <el-input v-model="formAdd.orginalPrice"></el-input>
                </el-form-item>
                <el-form-item label="介绍" prop="description">
                    <el-input type="textarea" v-model="formAdd.description"></el-input>
                </el-form-item>
                <el-form-item label="sku属性" prop="skuName">
                    <!--                    <el-cascader-->
                    <!--                            v-model="value"-->
                    <!--                            :options="categoryInfo"-->
                    <!--                            :props="cateListProps"-->
                    <!--                            clearable-->
                    <!--                            ref="cascader"-->

                    <!--                            @change="handleChange"></el-cascader>-->
                    <el-tree
                            ref="tree"
                            :data="categoryTree"
                            show-checkbox
                            node-key="id"
                            :default-expanded-keys="typeIds"
                            :default-checked-keys="typeIds"
                            :props="defaultProps">
                    </el-tree>
                </el-form-item>
                <el-form-item label="name" prop="name">
                    <!--                    级联选择-->
                    <el-cascader
                            ref="cascader1"
                            collapse-tags
                            :multiple="true"
                            v-model="value1"
                            clearable
                            @clearCheckedNodes="clearjilian"
                            :props="cateListProps1"
                            :options="categoryInfo"
                            @change="handleChange1"></el-cascader>
                </el-form-item>
                <el-form-item label="折扣力度" prop="discounts">
                    <el-input placeholder="0.5" v-model="formAdd.discounts"></el-input>
                </el-form-item>
                <el-form-item label="库存" prop="stock">
                    <el-input v-model="formAdd.stock"></el-input>
                </el-form-item>
                <el-dialog
                        width="30%"
                        title="内层 Dialog"
                        :visible.sync="innerVisible"
                        append-to-body>
                </el-dialog>
                <el-upload
                        class="upload-demo"
                        :action="baseUrl"
                        multiple
                        :limit="3"
                        :on-success="upload"
                >
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>

                <span slot="footer" class="dialog-footer">
<!--                    <el-button @click="innerVisible =true">详细信息添加</el-button>-->
    <el-button @click="dialogVisibleAdd = false">取 消</el-button>
    <el-button type="primary" @click="add()">确 定</el-button>
  </span>
            </el-dialog>
        </el-form>

        <!--        新增对话框结束-->

    </div>
</template>

<script>
    import Global from "../../../public/js/Global";

    export default {
        watch: {
            keywords: function (newval, oldval) {
                console.log(newval)
                console.log(oldval)
                this.keywords = newval;
                this.getInfo();
            }


        },
        data() {
            return {
                loading: true,
                defaultProps: {
                    children: 'children',
                    label: 'name'
                },
                addFlag: false,
                updateFlag: false,
                deleteFlag: false,
                cateListProps: {
                    value: 'id',                 //匹配响应数据中的id
                    label: 'name',               //匹配响应数据中的name
                    children: 'children',         //匹配响应数据中的children
                    checkStrictly: true
                },
                cateListProps1: {
                    value: 'id',                 //匹配响应数据中的id
                    label: 'name',               //匹配响应数据中的name
                    children: 'children',         //匹配响应数据中的children
                    checkStrictly: true
                },
                categoryInfo: [],
                options: [
                    {
                        value: '1',
                        label: '指南',
                        children: [
                            {
                                value: 2,
                                label: '1'
                            }
                        ]
                    }
                ],
                innerVisible: false,
                baseUrl: Global.baseUrl,
                categoryList: [],
                productList: [
                    // {
                    //     name: "xxxxx",
                    //     type: "222"
                    // }
                ],  // 分类数据
                dialogVisibleAdd: false,
                dialogVisibleEdit: false,
                formAdd: {  // 添加对话框
                    // name: "",
                    // typeImg: "",
                    // description: ""
                    categoryIds: []

                },
                formEdit: {  // 修改对话框
                    name: "",
                    id: 0,
                    img: "",
                    originalPrice: 0,
                    discounts: 0,
                    stock: 0

                },
                srcList: [],  // 放大
                ids: [],  // 批量删除数组
                currentPage4: 1,  // 当前页
                size: 6, // 每页的个数
                fileList: [],
                total: 100,// 总条数
                keywords: "", // 搜索关键字
                // rulesAdd: {
                //     name: [
                //         {required: true, message: '请输入分类', trigger: 'blur'},
                //         {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
                //     ],
                //     description: [
                //         {required: true, message: '请输入描述', trigger: 'blur'},
                //     ],
                //
                // },
                // rulesEdit: {
                //     name: [
                //         {required: true, message: '请输入分类', trigger: 'blur'},
                //         {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
                //     ],
                //     description: [
                //         {required: true, message: '请输入描述', trigger: 'blur'},
                //     ],
                // }
            }
        },
        created() {
            let permissionList = JSON.parse(localStorage.getItem('permissionList'))
            for (let i = 0; i < permissionList.length; i++) {
                if (this.$route.path == permissionList[i].permissionPath) {  // 如果当前的页面是当前遍历的权限数据
                    let children = permissionList[i].children;  // 就取出相应的数据
                    console.log(children)
                    for (let j = 0; j < children.length; j++) {
                        console.log(children[j].permissionCode)
                        if (children[j].permissionCode.indexOf('product:add') !== -1) { // 匹配到了
                            console.log('addtest')
                            this.addFlag = true;
                            console.log(this.addFlag)
                        } else if (children[j].permissionCode.indexOf('product:delete') !== -1) {
                            this.deleteFlag = true;
                        } else if (children[j].permissionCode.indexOf('product:update') !== -1) {
                            this.updateFlag = true;
                        }
                    }
                }
            }
            this.getInfo();
        },
        methods: {
            async addProduct() {
                this.dialogVisibleAdd = true;
                await this.$http.get('/admin/product/categorytree')
            },
            toEdit(id) {
                this.$router.push({
                    path: "/edit",
                    query: {
                        id: id
                    }
                })
            },
            toWrite(id) {
                console.log(id);
                this.$router.push({
                    path: "/write",
                    query: {
                        id: id
                    }
                })
            },
            clear() {
                this.$refs.cascader.$refs.panel.clearCheckedNodes()
            },
            handleChange(val) {
                console.log(val)
                let ids = []
                this.formAdd.categoryIds.push(val[1]);

            },
            handleChange1(val) {
                console.log(val)
                this.formAdd.categoryIds.push(val[1]);

            },
            async showEdit(row) {  // 展开修改对话框
                console.log(row)
                let {data: res} = await this.$http.get('/admin/product/getcategory?id=' + row.id)
                this.typeIds = res.data;
                // console.log(res)

                this.dialogVisibleEdit = true;

                this.formEdit.name = row.productName;
                this.formEdit.id = row.id;
                this.formEdit.img = row.skuImg;
                this.formEdit.categoryName = row.categoryName;
                this.formEdit.originalPrice = row.originalPrice;
                this.formEdit.discounts = row.discounts;
                this.formEdit.stock = row.stock;



                // this.$http.put('')
            },
            async getInfo() {  // 得到分类的信息

                let keywords = this.keywords || "";
                const {data: res} = await this.$http.get('/admin/product?index=' + this.currentPage4 + '&size=' + this.size
                    + "&keywords=" + keywords)
                console.log(res)
                if (res.meta.status === 200) {
                    this.loading = false
                } else {
                    this.loading = false
                    this.$message.error(res.meta.msg)
                }
                this.categoryTree = res.data.categoryTree
                this.total = res.data.total;
                this.productList = res.data.productList;
            },
            upload(response, file, fileList) { // 分类上传成功后的钩子
                this.formAdd.skuImg = response.data;  // 上传成功后的名字
            }
            ,
            uploadEdit(respose, file, fileList) {  // 编辑分类上传成功的钩子
                console.log(respose.data);
                this.formEdit.img = respose.data;  // 上传成功后的名字
                this.$forceUpdate()
            }
            ,
            async add() {  // 添加对话框里的确定
                // console.log(formAddRef);
                // let categoryIds = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys())
                let categoryIds = this.$refs.tree.getCheckedKeys()

                this.formAdd.categoryIds = categoryIds
                // console.log(this.formAdd)
                if (1) {
                    let {data: res} = await this.$http.post('/admin/product', this.formAdd)
                    console.log(res);
                    if (res.meta.status === 200) {
                        this.$message({
                            type: 'success',
                            message: '添加成功'
                        })
                        this.dialogVisibleAdd = false;
                        this.getInfo(); // 重新刷新数据
                        this.$forceUpdate();
                    } else {
                        this.$message({
                            type: 'error',
                            message: res.meta.msg
                        })
                        this.dialogVisibleAdd = false;
                    }

                } else {
                    this.$message({
                        type: 'error',
                        message: '请检查！'
                    })
                    return false;
                }
                // this.dialogVisibleAdd = true;

            }
            ,
            clearAdd() {  // 清除添加对话框的校验效果/上次表单信息
                // console.log(formAddRef)
                // this.$nextTick(() => {
                //     this.$refs[formAddRef].resetFields();
                //
                // })
                this.formAdd = {};
                this.$refs.cascader1.$refs.panel.clearCheckedNodes()

                this.$refs.cascader.$refs.panel.clearCheckedNodes()
                // this.categoryInfo=[];
                // console.log('22221321')
            },
            clearEdit() {
                this.formEdit.password = ""
                // this.$refs[formAddRef].resetFields();

            }
            ,
            async deleteCategory(row) {
                console.log(row);
                console.log(row.id)
                const {data: res} = await this.$http.delete('/admin/product/' + row.id)
                console.log(res);
                if (res.meta.status === 200) {
                    this.$message.success('删除成功！')
                    this.getInfo();
                    this.$forceUpdate()
                } else {
                    this.$message.error(res.meta.msg);
                }
            }
            ,
            async submitEdit() {  // 修改对话框确定按钮
                // console.log(row);
                // this.$nextTick(() => {
                    let categoryIds = this.$refs.treeEdit.getCheckedKeys()
                    console.log(categoryIds)
                    this.formEdit.categoryId = categoryIds;
                // })
                console.log(this.formEdit.categoryId)
                const {data: res} = await this.$http.put('/admin/product', this.formEdit);
                console.log(res.meta.status);
                if (res.meta.status === 200) {
                    this.$message.success("修改成功");
                    this.getInfo();
                    this.dialogVisibleEdit = false;
                } else {
                    this.$message.error(res.meta.msg);
                }
                this.dialogVisibleEdit = false;
            }
            ,
            handleSizeChange(size) { // 每页的个数
                this.size = size;
                this.getInfo()

            }
            ,
            handleCurrentChange(index) {
                this.currentPage4 = index;
                this.getInfo()

            }
            ,// 当前第几页
            handleSelectionChange(val) {  // 复选框
                console.log(val)
                for (let i = 0; i < val.length; i++) {
                    this.ids[i] = val[i].id;
                }
            }
            ,
            async deleteBatch() {  // 批量删除
                let length = this.ids.length
                if (length == 0) {
                    this.$message.info('请选择数据')
                    return;
                }
                console.log(this.ids)
                const {data: res} = await this.$http.post('/admin/product/deletebatch', this.ids);
                if (res.meta.status === 200) {
                    this.$message.success('批量删除成功！');
                    this.getInfo();
                    this.ids = []
                } else {
                    this.$message.error(res.meta.msg);
                }

            }
            ,
            async getTypeInfoByKey() {
                const {data: res} = await this.$http.post('/admin/type/', this.ids);

            }
        }
    }
</script>


<style scoped>
    /deep/ .el-button--mini, .el-button--mini.is-round {
        padding: 3px 8px;
    }
</style>